#include "TaskMgr.h"
#include "TTime.h"

void tmms::base::TaskMgr::onWork()
{
    std::lock_guard<std::mutex> lock(mtx_);
    int64_t now = TTime::NowMS();
    for(auto iter=tasks_.begin();iter!=tasks_.end();){
        if((*iter)->When()<now){
            (*iter)->Run();
            if((*iter)->When()<now){
                iter = tasks_.erase(iter);
                continue;
            }
        }
        iter++;
    }
}

bool tmms::base::TaskMgr::Add(TaskPtr &task)
{
    std::lock_guard<std::mutex> lock(mtx_);
    auto iter = tasks_.find(task);
    if(iter!=tasks_.end()){
        return false;//已经添加过任务；
    }
    tasks_.emplace(task);
    return true;
}
 
bool tmms::base::TaskMgr::Del(TaskPtr &task)
{
    std::lock_guard<std::mutex> lock(mtx_);
    tasks_.erase(task);
    return true;
}
